package fr.uniscol;

import fr.uniscol.model.Classe;
import fr.uniscol.model.Eleve;
import fr.uniscol.model.IUniscolUser;
import fr.uniscol.model.MEF;
import fr.uniscol.model.Matiere;
import fr.uniscol.model.Option;
import fr.uniscol.model.Periode;
import fr.uniscol.model.ProgrammeMEF;
import fr.uniscol.model.Scolarite;
import fr.uniscol.editors.PeriodePropertyEditor;
import fr.uniscol.mvc.SessionExpireeException;
import fr.uniscol.service.IClasseService;
import fr.uniscol.service.IEleveService;
import fr.uniscol.service.IReferenceMatieresService;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.codehaus.jackson.map.JsonSerializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ScolariteEleveController extends UniscolMainController {

    public static Logger log = Logger.getLogger(ScolariteEleveController.class);
    
	@Autowired
	private IEleveService eleveService;
	
	@Autowired
	private IClasseService classeService;
	
	@Autowired
	private IReferenceMatieresService referenceService;
	
	@RequestMapping("/eleve.scolarite.edit")
	public String editScolariteEleve(@RequestParam("eleveid") int eleveid, @RequestParam("scolariteid") int scolariteid, Model model, HttpSession session){
		
		Eleve eleve = eleveService.getEleveById(eleveid);
        
        eleve.setScolarites(eleveService.getScolaritesOfEleve(eleve));
        
		Scolarite scolarite = eleve.findScolariteById(scolariteid);
		
		if(scolarite == null){
			// Ajout d'une nouvelle
			scolarite = new Scolarite();
		}
		
		model.addAttribute("mefs", referenceService.findAllMEFAvailables(getUtilisateur(session).getBaseSelectionnee()));
        if(scolarite.getMef() != null){
            model.addAttribute("programmes", referenceService.findAllProgrammesByMEF(scolarite.getMef()));
        }
        
		model.addAttribute("classes", classeService.getAllClassesOfEtablissement(getUtilisateur(session).getBaseSelectionnee()));
		
		model.addAttribute("eleve", eleve);
		model.addAttribute("scolarite", scolarite);
		
		return "forms/scolariteForm";
	}
    
    @InitBinder
    public void initBinder(WebDataBinder binder, HttpServletRequest req){
        
        binder.registerCustomEditor(Periode.class, new PeriodePropertyEditor());
    }
    
    @RequestMapping(value = "/eleve.scolarite.save", method = RequestMethod.POST)
    public String saveScolariteEleve(@RequestParam("eleveid") long eleveid, 
                                     @RequestParam("scolariteid") long scolariteId, 
                                     @RequestParam("classeid") long classeId, 
                                     @RequestParam("mefid") long mefId,
                                     @RequestParam("option") String[] options,
                                     @RequestParam("periode") Periode periode,
                                     HttpSession session){
    //public String saveScolariteEleve(@ModelAttribute("scolarite") Scolarite scolarite, HttpSession session){
        
        Scolarite scolarite = new Scolarite();
        scolarite.setId(scolariteId);
        scolarite.setPeriode(periode);
        
        log.debug("PERIODE: " + periode);
        
        scolarite.setEleve(new Eleve());
        scolarite.getEleve().setId(eleveid);
        
        scolarite.setClasse(new Classe());
        scolarite.getClasse().setId(classeId);
        
        scolarite.setMef(new MEF());
        scolarite.getMef().setId(mefId);
        
        String[] split = null;
        for(int i = 0; i < options.length; i++){
            split = options[i].split("-");
            
            Option opt = new Option();
            opt.setMatiere(new Matiere());
            opt.getMatiere().setId(Long.parseLong(split[0]));
            
            opt.setModalite(split[1]);
            
            scolarite.getOptions().add(opt);
        }
        
        if(eleveService.saveScolariteEleve(scolarite)){
            alertSuccess("scolarite.save.ok", "la scolarité a été enregistrée avec succès", session);
        }else{
            alertError("scolarite.save.nok", "ECHEC de l'enregistrement de la scolarité !", session);
        }
        
        return "redirect:eleve.edit?eleveId=" + scolarite.getEleve().getId();
    }
    
    @RequestMapping("/eleve.scolarite.delete")
    public String deleteScolarite(@RequestParam("eleveid") long eleveId, @RequestParam("scolariteid") long scolariteId, HttpSession session){
        
        Scolarite scolarite = new Scolarite();
        scolarite.setId(scolariteId);
        
        if(eleveService.deleteScolariteEleve(scolarite)){
            alertSuccess("scolarite.delete.ok", "la scolarité a été supprimée avec succès", session);
        }else{
            alertError("scolarite.delete.nok", "ECHEC de la suppression de la scolarité !", session);
        }
        
        return "redirect:eleve.edit?eleveId=" + eleveId;
    }
    
    @RequestMapping("/eleve.scolarite.getprogrammes")
    public @ResponseBody List<ProgrammeMEF> getProgrammesOfMef(@RequestParam("mefid") int mefid, @RequestParam(required = false, value = "modalites") String[] modalites){
        
        MEF mef = referenceService.getMEFById(mefid);
        if(mef != null){
            List<ProgrammeMEF> programmes = referenceService.findAllProgrammesByMEF(mef);
            List<ProgrammeMEF> programmesFiltres = new ArrayList<ProgrammeMEF>();
            
            for(ProgrammeMEF p : programmes){
                if(modalites != null){
                    for(int i = 0; i < modalites.length; i++){
                        if(p.getModalite().equals(modalites[i])){
                            programmesFiltres.add(p);
                        }
                    }
                }else{
                    programmesFiltres.add(p);
                }
            }
            
            return programmesFiltres;
            
        }else{
            return null;
        }
    }
}
